package tk.mybatis.springboot.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.springboot.common.KeCongResult;
import tk.mybatis.springboot.common.TaskUtil;
import tk.mybatis.springboot.entity.CustomizedTask;
import tk.mybatis.springboot.mapper.TaskMapper;
import tk.mybatis.springboot.service.TaskService;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TaskServiceImpl implements TaskService {

    //添加移动任务
    public static final String URL_MOVE_TASK = TaskUtil.PREV_URL+ "api/fms/addMoveTask";

    public static final String ALL_TASK_STATUS = TaskUtil.PREV_URL+"api/fms/allTaskStatus";
    //添加自定义任务
    public static final String URL_ADD_TASK = TaskUtil.PREV_URL+ "api/fms/addTask";

    //删除任务
    public static final String URL_DEL_TASK = TaskUtil.PREV_URL+"api/fms/deleteTask";

    //暂停任务
    public static final String URL_PUS_TASK = TaskUtil.PREV_URL+"api/fms/pauseTask";

    //启动暂停的舞蹈
    public static final String URL_RSM_TASK = TaskUtil.PREV_URL+"api/fms/resumeTask";
    public static final String URL_CPL_TASK = TaskUtil.PREV_URL+"api/fms/completeTask";

    //查询所有车辆
    public static final String ALL_VEHICLE_STATUS = TaskUtil.PREV_URL+"api/fms/allVehicleStatus";


    @Autowired
    TaskMapper taskMapper;


    @Override
    public KeCongResult pauseTask(String TaskNo) {

        CloseableHttpResponse httpResponse = null;
        Map<String,String> param = new HashMap<>();
        param.put("TaskNo",TaskNo);
        try {
            httpResponse = TaskUtil.httpPost(URL_PUS_TASK, param);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity entity = httpResponse.getEntity();
                String jsonString = EntityUtils.toString(entity);
                KeCongResult keCongResult = JSONUtil.toBean(jsonString,KeCongResult.class,true);
                return keCongResult;
            }else{
                System.out.println("访问添加自定义任务网络不通");
            }

        } catch (IOException e) {
            System.out.println("錯誤信息是："+e.getMessage());
            throw new RuntimeException(e);
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public KeCongResult resumeTask(String TaskNo) {
        CloseableHttpResponse httpResponse = null;
        Map<String,String> param = new HashMap<>();
        param.put("TaskNo",TaskNo);
        try {
            httpResponse = TaskUtil.httpPost(URL_RSM_TASK, param);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity entity = httpResponse.getEntity();
                String jsonString = EntityUtils.toString(entity);
                KeCongResult keCongResult = JSONUtil.toBean(jsonString,KeCongResult.class,true);
                return keCongResult;
            }else{
                System.out.println("访问添加自定义任务网络不通");
            }

        } catch (IOException e) {
            System.out.println("錯誤信息是："+e.getMessage());
            throw new RuntimeException(e);
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public KeCongResult completeTask(String TaskNo) {
        CloseableHttpResponse httpResponse = null;
        Map<String,String> param = new HashMap<>();
        param.put("TaskNo",TaskNo);
        try {
            httpResponse = TaskUtil.httpPost(URL_CPL_TASK, param);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity entity = httpResponse.getEntity();
                String jsonString = EntityUtils.toString(entity);
                KeCongResult keCongResult = JSONUtil.toBean(jsonString,KeCongResult.class,true);
                return keCongResult;
            }else{
                System.out.println("访问添加自定义任务网络不通");
            }

        } catch (IOException e) {
            System.out.println("錯誤信息是："+e.getMessage());
            throw new RuntimeException(e);
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public int saveTask(CustomizedTask task) {
        if(task.TaskNo==null) task.TaskNo=IdUtil.simpleUUID();
        if(task.FinishAction==null) task.FinishAction=1;
        if(task.Priority==null) task.Priority=2;
        if(task.Discharge_height==null) task.Discharge_height="5300mm";
        if(task.Location==null) task.Location=task.Unloading_point;

        return taskMapper.saveTask(task);
    }

    @Override
    public KeCongResult allVehicleStatus() {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(ALL_VEHICLE_STATUS);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);

            // 检查响应状态码
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 解析响应内容
                String responseBody = EntityUtils.toString(httpResponse.getEntity());
                // 在此处处理解析后的响应数据
                System.out.println("响应内容: " + responseBody);
                KeCongResult keCongResult = JSONUtil.toBean(responseBody,KeCongResult.class,true);
                return keCongResult;
            } else {
                System.err.println("请求失败，状态码: " + statusCode);
            }
        } catch (IOException e) {
            System.out.println("錯誤信息是："+e.getMessage());
            e.printStackTrace();
        } finally {
            // 释放资源
            httpClient.getConnectionManager().shutdown();
        }

        return null;
    }


    @Override
    public KeCongResult postAddTask(CustomizedTask task) {
        if(task.TaskNo==null){
            task.TaskNo = IdUtil.simpleUUID();
        }

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = TaskUtil.httpPost(URL_ADD_TASK, task);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity entity = httpResponse.getEntity();
                String jsonString = EntityUtils.toString(entity);
                KeCongResult keCongResult = JSONUtil.toBean(jsonString,KeCongResult.class,true);
                return keCongResult;
            }else{
                System.out.println("访问添加自定义任务网络不通");
            }

        } catch (IOException e) {
            System.out.println("錯誤信息是："+e.getMessage());
            throw new RuntimeException(e);
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public KeCongResult postDeleteTask(CustomizedTask task) {
        return null;
    }

    @Override
    public List<CustomizedTask> getTaskByPoint(Map<String, Integer> poinMap) {

        return taskMapper.getTaskByPoint(poinMap);

    }

    @Override
    public KeCongResult allTaskStatus() {
        HttpClient httpClient = HttpClientBuilder.create().build();

        HttpGet httpGet = new HttpGet(ALL_TASK_STATUS);

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            // 检查响应状态码
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 解析响应内容
                String jsonString = EntityUtils.toString(httpResponse.getEntity());
                // 在此处处理解析后的响应数据
                System.out.println("响应内容: " + jsonString);
                KeCongResult keCongResult = JSONUtil.toBean(jsonString,KeCongResult.class,true);
                return keCongResult;
            } else {
                System.err.println("请求失败，状态码: " + statusCode);
            }

        } catch (IOException e) {
            System.out.println("錯誤信息是："+e.getMessage());
            throw new RuntimeException(e);
        }finally {
            // 释放资源
            httpClient.getConnectionManager().shutdown();
        }

        return null;
    }

    @Override
    public KeCongResult addMoveTask(CustomizedTask task) {

        // 创建 CloseableHttpClient
        CloseableHttpResponse httpResponse = null;

        try {
            httpResponse = TaskUtil.httpPost(URL_MOVE_TASK, task);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity entity = httpResponse.getEntity();
                String jsonString = EntityUtils.toString(entity);
                KeCongResult keCongResult = JSONUtil.toBean(jsonString,KeCongResult.class,true);
                return keCongResult;
            }else{
                System.out.println("访问添加自定义任务网络不通");
            }
//          if(httpResponse==null){
//              System.out.println("访问添加自定义任务网络不通");
//          }
        } catch (IOException e) {
            System.out.println("錯誤信息是："+e.getMessage());
            throw new RuntimeException(e);
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return null;
    }

    @Override
    public List<CustomizedTask> findAllTask() {

        return taskMapper.findAllTask();
    }


}
